﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using System.Net.NetworkInformation;

namespace TripleTriad
{
    public partial class CreateAccount : PhoneApplicationPage
    {

        //storage dell'applicazione
        private static IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings;

        //dati del form
        private string user = "";
        private string psw = "";
        private string mail = "";

        //id del nuovo utente
        private string idnewuser;

        public CreateAccount()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            buttonCrea.IsEnabled = false;
        }

        private void buttonCrea_Tap(object sender, GestureEventArgs e)
        {
            bool isCorrect = true;

            //raccolgo i campi
            user = userBox.Text.ToString().ToLower();
            string psw1 = psw1Box.Password;
            string psw2 = psw2Box.Password;
            mail = mailBox.Text.ToString();
            psw = psw1;

            //controllo validità doppia password
            if (psw1 != "" && psw2 != "")
            {
                if (psw1 != psw2)
                    isCorrect = false; //password doppia non corretta
            }
            else
                isCorrect = false;

            //controllo user, tolgo i caratteri che mi servono successivamente
            if (user != "")
            {
                user.Replace('|', '/');
                user.Replace('§', 'ç');
            }
            else
                isCorrect = false;

            //controllo mail
            if (mail != "")
            {
                var regEx = new System.Text.RegularExpressions.Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
                if (regEx.IsMatch(mail) == false)
                    isCorrect = false;//mail non corretta
            }
            else
                isCorrect = false;

            if (isCorrect)
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/createAccount.php");
                    HttpWebRequest createRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                    createRequest.Method = "POST";
                    createRequest.ContentType = "application/x-www-form-urlencoded";
                    createRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackCreateAccount), createRequest);
                }
                else
                {
                    MessageBox.Show("Connection error, please retry later.");
                }
            }
            else
            {
                MessageBox.Show("Dati Inseriti non Corretti");
            }
        }

        private void GetRequestStreamCallbackCreateAccount(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);

            // Create the post data
            string postData = "apikey=k3kk0puzz4&user=" + user.ToString() + "&psw=" + psw.ToString() + "&mail=" + mail.ToString();
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackCreateAccount), myRequest);
        }//GetRequestStreamCallbackCreateAccount

        private void GetResponsetStreamCallbackCreateAccount(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingCreateAccount(result));
            }
        }//GetResponsetStreamCallbackCreateAccount

        private void ParsingCreateAccount(string result)
        {
            string[] ris = majorSplit(result);
            ris = minorSplit(ris[0]);//sono sicuro che rappresenta un solo record

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else //se login effettuato
            {
                idnewuser = result;

                Uri myDBuri = new Uri("http://www.tripletriad.altervista.org/firstCards.php");
                HttpWebRequest createRequest = (HttpWebRequest)HttpWebRequest.Create(myDBuri);
                createRequest.Method = "POST";
                createRequest.ContentType = "application/x-www-form-urlencoded";
                createRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackFirstCards), createRequest);
            }
        }//ParsingCreateAccount

        private void GetRequestStreamCallbackFirstCards(IAsyncResult callbackResult)
        {
            HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
            // End the stream request operation
            Stream postStream = myRequest.EndGetRequestStream(callbackResult);

            // Create the post data
            string postData = "apikey=k3kk0puzz4&ID=" + idnewuser;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            // Start the web request
            myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallbackFirstCards), myRequest);
        }//GetRequestStreamCallbackFirstCards

        private void GetResponsetStreamCallbackFirstCards(IAsyncResult callbackResult)
        {
            HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
            using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = httpWebStreamReader.ReadToEnd();
                Dispatcher.BeginInvoke(() => ParsingFirstCards(result));
            }
        }//GetResponsetStreamCallbackFirstCards

        private void ParsingFirstCards(string result)
        {
            string[] ris = majorSplit(result);
            ris = minorSplit(ris[0]);//sono sicuro che rappresenta un solo record

            if (ris[0] == "ERRORE")
            {
                MessageBox.Show(ris[1]);
            }
            else //se login effettuato
            {
                 //aggiungo i dati in locale
                appSettings.Add("username", user);

                //torno indietro alla main page
                NavigationService.GoBack();//cambio della pagina
            }
        }//ParsingCreate

        //splitta la stringa passata in base a |
        private string[] minorSplit(string result)
        {
            return result.Split('|');
        }

        //splitta la stringa passata in base a §
        private string[] majorSplit(string result)
        {
            return result.Split('§');
        }
    }
}